﻿using LYR_RPA.utils;
using System;
using System.IO;
using System.Windows.Controls;
using System.Windows.Forms;
using ClosedXML.Excel;
using System.Windows.Input;
using System.Collections.Generic;
using System.Linq;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Drawing.Charts;
using LYR_RPA.models.project;
using LYR_RPA.dialog;
using System.CodeDom.Compiler;

namespace LYR_RPA.pages.home
{
    /// <summary>
    /// LogPage.xaml 的交互逻辑
    /// </summary>
    public partial class LogPage : System.Windows.Controls.Page
    {
        public LogPage()
        {
            InitializeComponent();
            LogDataGrid.ItemsSource = CommonUtils.ReadLog() ;
        }

        private void ClearLog_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SQLiteApply.ClearLogs();
            CommonUtils.ReadLog();
        }

        private void Export_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // 用户选择导出路径
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Title = "Save Excel File",
                Filter = "Excel Workbook|*.xlsx;*.xls",
                DefaultExt = "xlsx"
            };
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string outputPath = saveFileDialog.FileName;
                try
                {
                    if (!string.IsNullOrEmpty(outputPath))
                    {
                        using (var workbook = new XLWorkbook())
                        {
                            // 添加一个工作表
                            var worksheet = workbook.Worksheets.Add("Sheet1");

                            List<string> lists = new List<string>() { "序号", "名称", "路径" , "结果", "颜色", "是否执行", "调用方式", "是否等待" , "是否取消","异常情况", "执行时间", "结束时间" };
                            for (int index=0;index<lists.Count;index++)
                            {
                                // 在工作表中添加一些数据
                                worksheet.Cell(1, index+1).Value = lists[index];
                                // 设置标题单元格的样式
                                // 设置列宽
                                worksheet.Column(index + 1).Width = 20;
                                worksheet.Row(index+1).Height = 20;
                                var cell = worksheet.Cell(1, index+1);
                                cell.Style.Font.Bold = true; // 设置字体加粗
                                cell.Style.Font.FontColor = XLColor.White; // 设置字体加粗
                                cell.Style.Fill.BackgroundColor = XLColor.LightBlue; // 设置背景颜色为浅蓝色
                                cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; // 设置水平居中对齐
                                cell.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center; // 设置水平居中对齐
                                cell.Style.Border.OutsideBorderColor = XLColor.Black; // 设置边框颜色为黑色
                            }
                            int row = 2;
                            foreach (var item in CommonUtils.ReadLog())
                            {
                                worksheet.Cell(row, 1).Value = item.Id;
                                worksheet.Cell(row, 2).Value = item.Name;
                                worksheet.Cell(row, 3).Value = item.Path;
                                worksheet.Cell(row, 4).Value = item.Msg;
                                worksheet.Cell(row, 5).Value = item.State;
                                worksheet.Cell(row, 6).Value = item.IsExecute;
                                worksheet.Cell(row, 7).Value = item.IsCommand ? "远程" : "本地";
                                worksheet.Cell(row, 8).Value = item.IsAwait ? "定时执行" : "立即执行";
                                worksheet.Cell(row, 9).Value = item.IsCancel;
                                worksheet.Cell(row, 10).Value = item.ErrersString;
                                worksheet.Cell(row, 11).Value = item.CreateTime;
                                worksheet.Cell(row, 12).Value = item.ExecuteTime;
                                foreach(int idx in Enumerable.Range(1, 12))
                                {
                                    var cell = worksheet.Cell(row, idx);
                                    cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; // 设置水平居中对齐
                                    cell.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center; // 设置水平居中对齐
                                }
                                row++;
                            }
                            // 保存工作簿到文件
                            workbook.SaveAs(outputPath);
                            new DialogBox().ShowMessage("导出结果", "导出完毕！", "确定");
                        }

                    }
                }catch (FileNotFoundException ex)
                {
                    Console.WriteLine(ex.Message);
                    new DialogBox().ShowMessage("导出结果", "导出失败！", "确定");
                }
                

            }
        }

        private void Search_SearchStarted(object sender, HandyControl.Data.FunctionEventArgs<string> e)
        {
            if (string.IsNullOrEmpty(Search.Text))
            {
                CommonUtils.ReadLog();
            }
            else
            {
                CommonUtils.SearchLog(Search.Text);
            }
        }

        private void Search_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (string.IsNullOrEmpty(Search.Text))
                {
                    CommonUtils.ReadLog();
                }
                else
                {
                    CommonUtils.SearchLog(Search.Text);
                }
            }
        }


        private void LogDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var execute = LogDataGrid.SelectedItem as Execute;
            if (execute != null)
            {
                if (!execute.ErrersString.TrimStart("{}".ToCharArray()).Trim().Equals(""))
                {
                    new DialogBox().ShowMessage("异常信息", execute.ErrersString, "确定");
                }
            }

        }
    }
}
